package com.atguigu.gulimall.order.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author : xyq
 * @Description: 登录拦截器
 * @date: 2020/8/10/17:51
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    /**
     * 使用ThreadLocal来共享数据（登录的用户信息），其他线程都能获取到
     */
    public static ThreadLocal<MemberResponseVo> loginUser = new ThreadLocal<>();

    /**
     * 目标请求到达之前的前置拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取登录的用户信息
        MemberResponseVo memberVo = (MemberResponseVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberVo != null) {
            loginUser.set(memberVo);
            return true;
        } else {
            request.getSession().setAttribute("msg", "请先进行登录");
            // 未登录，拦截重定向
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
